package com.lj.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.common.constant.BaseConstant;
import com.lj.common.core.model.system.SysDictData;
import com.lj.common.core.model.system.SysDictType;
import com.lj.common.core.redis.RedisCache;
import com.lj.system.constants.DictConstants;
import com.lj.system.mapper.SysDictDataMapper;
import com.lj.system.service.ISysDictDataService;
import com.lj.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;


/**
 * 字典数据服务实现类
 *
 * @author 小李飞刀
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

    @Resource
    private RedisCache<String, List<SysDictData>> redisCache;

    @Resource
    private ISysDictTypeService dictTypeService;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }


    /**
     * 根据字典类型查询字典值列表
     *
     * @param dictType 字典类型
     * @return 字典数据列表
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        // 从缓存中获取
        List<SysDictData> list = redisCache.getCacheObject(getCacheKey(dictType));
        // 存在直接返回
        if (CollUtil.isNotEmpty(list)) {
            return list;
        }
        return getByType(dictType);
    }


    /**
     * 加载字典数据到缓存
     */
    private void loadingDictCache() {
        // 查询所有字典类型
        List<SysDictType> dictTypeList = dictTypeService.list();
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDataList = getByType(dictType.getDictType());
            redisCache.setCacheObject(getCacheKey(dictType.getDictType()), dictDataList);
        }
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return BaseConstant.SYS_DICT_KEY + configKey;
    }

    /**
     * 根据类型查询数据列表
     *
     * @param dictType 字典类型
     * @return 数据列表
     */
    private List<SysDictData> getByType(String dictType) {
        QueryWrapper<SysDictData> wrapper = Wrappers.query();
        wrapper.eq(DictConstants.COLUMN_DICT_TYPE, dictType).eq(DictConstants.COLUMN_STATUS, DictConstants.STATUS_NORMAL).orderByAsc(DictConstants.COLUMN_DICT_SORT);
        return list(wrapper);
    }
}
